import requests
import datetime
from config import TELEGRAM, ENV


def print_trade_analysis(analyzer):
    # Get the results we are interested in
    if not analyzer.get( "total" ):
        return

    total_open = analyzer.total.open
    total_closed = analyzer.total.closed
    total_won = analyzer.won.total
    total_lost = analyzer.lost.total
    win_streak = analyzer.streak.won.longest
    lose_streak = analyzer.streak.lost.longest
    pnl_net = round( analyzer.pnl.net.total, 2 )
    strike_rate = round( (total_won / total_closed) * 2 )

    # Designate the rows
    h1 = ['Total Open', 'Total Closed', 'Total Won', 'Total Lost']
    h2 = ['Strike Rate', 'Win Streak', 'Losing Streak', 'PnL Net']
    r1 = [total_open, total_closed, total_won, total_lost]
    r2 = [strike_rate, win_streak, lose_streak, pnl_net]

    # Check which set of headers is the longest.
    if len( h1 ) > len( h2 ):
        header_length = len( h1 )
    else:
        header_length = len( h2 )

    # Print the rows
    print_list = [h1, r1, h2, r2]
    row_format = "{:<15}" * (header_length + 1)
    print( "Trade Analysis Results:" )
    for row in print_list:
        print( row_format.format( '', *row ) )


def print_sqn(analyzer):
    sqn = round( analyzer.sqn, 2 )
    print( 'SQN: {}'.format( sqn ) )


def send_telegram_message(message="", force = False):
    if not force and ENV != "production":
        return

    proxies = {
        'http': 'http://127.0.0.1:8001',
        'https': 'http://127.0.0.1:8001',
    }

    base_url = "https://api.telegram.org/bot%s" % TELEGRAM.get( "bot" )
    return requests.get( "%s/sendMessage" % base_url, params={
        'chat_id': TELEGRAM.get( "channel" ),
        'text': message
    }, proxies=proxies )


# UTC时间转为上海时间
def utc2local(utctime, UTC_FORMAT="%Y-%m-%dT%H:%M:%S.%fZ"):
    utcTime = datetime.datetime.strptime( utctime, UTC_FORMAT )
    localtime = utcTime + datetime.timedelta( hours=8 )
    return localtime


# 通知最近5分钟内产生的交易信号
def notify_signal(signal_type, _datetime, price=None):
    '''
    The argument ``type`` can be:
        - ``NOTICE``
        - ``BUY``
        - ``SELL``
    '''

    timedelta = datetime.datetime.now() - _datetime
    # print( datetime.datetime.now() )
    # print( timedelta.total_seconds() )
    offset_seconds = int( timedelta.total_seconds() )
    message = '[{}] {} signal generated,price {}, offset {}s.'.format( _datetime.strftime( "%y-%m-%d %H:%M" ),
                                                                       signal_type,
                                                                       price,
                                                                       offset_seconds )
    print( message )

    # send_telegram_message( message, True )
    if (offset_seconds < 60 * 10):
        send_telegram_message( message, True)
    return True
